﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Sharp.ServiceContracts;
using System.Diagnostics;
using Sharp.Infrastructure.WebApiClient;

namespace Sharp.Portal.Owin
{
    [DebuggerStepThrough]
    public class SharpUserStore : IUserStore<SharpUser, int>,
                                 IUserPasswordStore<SharpUser, int>,
                                 IUserClaimStore<SharpUser, int>,
                                 IUserLockoutStore<SharpUser, int>,
                                 IUserEmailStore<SharpUser, int>,
                                 IUserPhoneNumberStore<SharpUser, int>,
                                 IUserTwoFactorStore<SharpUser, int>
    {

        /// <summary>
        /// 声明
        /// </summary>
        public IList<Claim> Claims = null;

        /// <summary>
        /// 实例化
        /// </summary>
        public SharpUserStore()
        {
            //声明
            Claims = new List<Claim>();
        }

        /// <summary>
        /// 用户
        /// </summary>
        public SharpUser UserIdentity = null;


        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task CreateAsync(SharpUser user)
        {
            return Task.Run(() =>
            {
                using (var proxy = new WebApiClientServiceProxy<IUserService>())
                {
                    proxy.Channel.SaveUser(user);
                }
            });
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task DeleteAsync(SharpUser user)
        {
            return Task.Run(() =>
            {
                using (var proxy = new WebApiClientServiceProxy<IUserService>())
                {
                    proxy.Channel.DeleteUsers(new[] { user.Id });
                }
            });
        }

        /// <summary>
        /// 2>通过用户ID，获取用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public Task<SharpUser> FindByIdAsync(int userId)
        {
            return Task.Run(() =>
          {
              if (UserIdentity != null)
              {
                  if (UserIdentity.Permissions == null || !UserIdentity.Permissions.Any())
                  {
                      using (var proxy = new WebApiClientServiceProxy<IUserService>())
                      {
                          UserIdentity.Permissions = proxy.Channel.GetPermissionById(userId).Result.ToList();

                      }
                  }
                  return UserIdentity;
              }

              using (var proxy = new WebApiClientServiceProxy<IUserService>())
              {
                  var res = proxy.Channel.GetUserByKey(userId);

                  res.Data.Permissions = proxy.Channel.GetPermissionById(userId).Result.ToList();
                  return UserIdentity = new SharpUser(res.Data);
              }
          });
        }

        /// <summary>
        /// 1>通过用户名获取用户信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public Task<SharpUser> FindByNameAsync(string userName)
        {
            return Task.Run(() =>
            {
                if (UserIdentity != null) { return UserIdentity; }

                using (var proxy = new WebApiClientServiceProxy<IUserService>())
                {
                    var res = proxy.Channel.GetUserByName(userName);

                    return UserIdentity = new SharpUser(res.Data);
                }
            });
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task UpdateAsync(SharpUser user)
        {
            return Task.Run(() =>
            {

            });
        }

        /// <summary>
        /// 释放
        /// </summary>
        public void Dispose()
        {
        }

        /// <summary>
        /// 获取密码
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task<string> GetPasswordHashAsync(SharpUser user)
        {
            return Task.Run(() =>
            {
                return user.Password;
            });
        }

        /// <summary>
        /// 是否有密码
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task<bool> HasPasswordAsync(SharpUser user)
        {
            return Task.FromResult<bool>(!string.IsNullOrEmpty(user.Password));
        }

        /// <summary>
        /// 密码进行加密
        /// </summary>
        /// <param name="user"></param>
        /// <param name="passwordHash"></param>
        /// <returns></returns>
        public Task SetPasswordHashAsync(SharpUser user, string passwordHash)
        {
            return Task.Run(() =>
            {
                user.Password = passwordHash;//加密后
            });
        }


        /// <summary>
        /// 添加一个声明
        /// </summary>
        /// <param name="user"></param>
        /// <param name="claim"></param>
        /// <returns></returns>
        public Task AddClaimAsync(SharpUser user, Claim claim)
        {
            return Task.Run(() =>
            {
                Claims.Add(claim);
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task<IList<Claim>> GetClaimsAsync(SharpUser user)
        {
            return Task.Run(() =>
            {
                IList<Claim> list = new List<Claim>();

                //list.Add(new Claim("permissions", user.Permissions.ToJson()));
                return list;
            });
        }

        /// <summary>
        /// 移除声明
        /// </summary>
        /// <param name="user"></param>
        /// <param name="claim"></param>
        /// <returns></returns>
        public Task RemoveClaimAsync(SharpUser user, Claim claim)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取访问失败次数
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task<int> GetAccessFailedCountAsync(SharpUser user)
        {
            return Task.FromResult(1);
        }

        /// <summary>
        /// 获取锁定状态
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task<bool> GetLockoutEnabledAsync(SharpUser user)
        {
            return Task.Run<bool>(() => false);
        }

        /// <summary>
        /// 获取锁定结束时间
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task<DateTimeOffset> GetLockoutEndDateAsync(SharpUser user)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 增加访问失败次数s
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task<int> IncrementAccessFailedCountAsync(SharpUser user)
        {
            return Task.Run(() =>
            {
                using (var proxy = new WebApiClientServiceProxy<IUserService>())
                {
                    var res = proxy.Channel.IncrementAccessFailedCount(user.Id);

                    return res.Data;
                }
            });
        }

        /// <summary>
        /// 重置访问失败计数
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task ResetAccessFailedCountAsync(SharpUser user)
        {
            return Task.Run(() =>
            {
                using (var proxy = new WebApiClientServiceProxy<IUserService>())
                {
                    proxy.Channel.ResetAccessFailedCount(user.Id);
                }
            });
        }

        #region  LockOut
        /// <summary>
        /// 设置锁定与否
        /// </summary>
        /// <param name="user"></param>
        /// <param name="enabled"></param>
        /// <returns></returns>
        public Task SetLockoutEnabledAsync(SharpUser user, bool enabled)
        {
            return Task.Run(() =>
            {
                using (var proxy = new WebApiClientServiceProxy<IUserService>())
                {
                    proxy.Channel.SetLockoutEnabled(user.Id, enabled);
                }
            });
        }

        /// <summary>
        /// 设置锁定时间
        /// </summary>
        /// <param name="user"></param>
        /// <param name="lockoutEnd"></param>
        /// <returns></returns>
        public Task SetLockoutEndDateAsync(SharpUser user, DateTimeOffset lockoutEnd)
        {
            return Task.Run(() =>
            {
                using (var proxy = new WebApiClientServiceProxy<IUserService>())
                {
                    proxy.Channel.SetLockoutEndDate(user.Id, lockoutEnd);
                }
            });
        }
        #endregion

        #region Email

        /// <summary>
        /// 通过邮箱获取用户信息
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public Task<SharpUser> FindByEmailAsync(string email)
        {
            return Task.Run(() =>
            {
                if (UserIdentity != null) { return UserIdentity; }

                using (var proxy = new WebApiClientServiceProxy<IUserService>())
                {
                    var res = proxy.Channel.GetUserByEmail(email);

                    return UserIdentity = new SharpUser(res.Data);
                }
            });
        }

        /// <summary>
        /// 获取用户邮箱
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<string> GetEmailAsync(SharpUser user)
        {
            if (user.Email.IsNullOrEmpty())
            {
                var u = await FindByIdAsync(user.Id);
                return u.Email;
            }
            return user.Email;
        }

        /// <summary>
        /// 确认邮件
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task<bool> GetEmailConfirmedAsync(SharpUser user)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 修改邮箱
        /// </summary>
        /// <param name="user"></param>
        /// <param name="email"></param>
        /// <returns></returns>
        public Task SetEmailAsync(SharpUser user, string email)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="confirmed"></param>
        /// <returns></returns>
        public Task SetEmailConfirmedAsync(SharpUser user, bool confirmed)
        {
            throw new NotImplementedException();
        }


        #endregion

        #region Phone

        /// <summary>
        /// 获取手机号
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task<string> GetPhoneNumberAsync(SharpUser user)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task<bool> GetPhoneNumberConfirmedAsync(SharpUser user)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public Task SetPhoneNumberAsync(SharpUser user, string phoneNumber)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="confirmed"></param>
        /// <returns></returns>
        public Task SetPhoneNumberConfirmedAsync(SharpUser user, bool confirmed)
        {
            throw new NotImplementedException();
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Task<bool> GetTwoFactorEnabledAsync(SharpUser user)
        {
            return Task.Run<bool>(() =>
            {
                return false;
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="enabled"></param>
        /// <returns></returns>
        public Task SetTwoFactorEnabledAsync(SharpUser user, bool enabled)
        {
            return Task.Run(() =>
            {

            });
        }
    }
}